<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入试卷名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="试卷总分" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入试卷总分" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="建议答题时间，单位分钟" prop="suggestTime">
        <el-input v-model="queryParams.suggestTime" placeholder="请输入建议答题时间，单位分钟" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="是否删除，1表示已删除" prop="deleted">
        <el-input v-model="queryParams.deleted" placeholder="请输入是否删除，1表示已删除" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!--      <el-form-item label="工种类别" prop="jobCategory">-->
      <!--        <el-select v-model="queryParams.jobCategory" placeholder="请选择工种类别，运营类等" clearable>-->
      <!--          <el-option v-for="dict in dict.type.job_category" :key="dict.value" :label="dict.label" :value="dict.value" />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="题库" prop="outline">-->
      <!--        <el-input v-model="queryParams.outline" placeholder="请输入题库关键字" clearable @keyup.enter.native="handleQuery" />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['exam:paper:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['exam:paper:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['exam:paper:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['exam:paper:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键，试卷ID" align="center" prop="id" /> -->
      <el-table-column label="试卷名称" align="center" prop="name" />
      <el-table-column label="试卷总分" align="center" prop="score" />
      <el-table-column label="建议答题时间" align="center" prop="suggestTime" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <!-- <el-table-column label="是否删除，1表示已删除" align="center" prop="deleted" /> -->
      <!--      <el-table-column label="工种类别" align="center" prop="jobCategory">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.job_category" :value="scope.row.jobCategory" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="题库" align="center" prop="outline" show-overflow-tooltip />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:paper:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['exam:paper:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改考试试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body center>
      <el-row :gutter="20">
        <!-- 左侧表单区域 -->
        <el-col :span="8">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <!-- 智能生成按钮 -->
            <div class="smart-generate-btn">
              <el-button type="primary" icon="el-icon-magic-stick" @click="openSmartGenerate">
                智能生成试题
              </el-button>
            </div>
            <el-form-item label="试卷名称" prop="name" required>
              <el-input v-model="form.name" placeholder="请输入试卷名称" />
            </el-form-item>
            <el-form-item label="建议答题时间" prop="suggestTime" required>
              <div style="display: flex; align-items: center;">
                <el-input-number v-model="form.suggestTime" :step="10" style="width: 150px;" />
                <span style="margin-left: 8px;">分钟</span>
              </div>
            </el-form-item>
            <el-form-item label="试卷总分" prop="score">
              <el-statistic v-model="form.score" placeholder="请输入试卷总分" />
            </el-form-item>
            <!-- <el-form-item label="题库" prop="outline">
              <el-input v-model="form.outline" type="text" placeholder="请输入题库" />
            </el-form-item> -->

            <!-- 已选题目列表 -->
            <div class="selected-questions-title">已选题目</div>
            <el-table v-loading="paperQuestionloading" ref="paperQuestionTable" :data="form.examPaperQuestions"
              :default-sort="{ prop: 'questionType', order: 'ascending' }" height="400px">
              <el-table-column label="题型" align="center" prop="questionType" width="100">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.exam_question_type" :value="scope.row.questionType" />
                </template>
              </el-table-column>
              <el-table-column label="题目名称" align="center" prop="questionTitle" show-overflow-tooltip />
              <el-table-column label="分值" align="center" prop="questionScore" width="80" />
              <el-table-column label="操作" align="center" width="80">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handlePaperQuestionDelete(scope.row)"
                    v-hasPermi="['exam:paper_question:remove']">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-col>

        <!-- 右侧题目选择区域 -->
        <el-col :span="16">
          <div class="question-select-area">
            <el-form :model="questionQueryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
              <el-form-item label="题型" prop="questionType">
                <el-select v-model="questionQueryParams.questionType" placeholder="请选择题目类型" clearable>
                  <el-option v-for="dict in dict.type.exam_question_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <!--              <el-form-item label="所属大类" prop="jobCategory">-->
              <!--                <el-select v-model="questionQueryParams.jobCategory" placeholder="请选择类型" clearable>-->
              <!--                  <el-option v-for="dict in dict.type.job_category" :key="dict.value" :label="dict.label"-->
              <!--                    :value="dict.value" />-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
              <el-form-item label="题库" prop="outline">
                <el-input v-model="questionQueryParams.outline" placeholder="请输入题库关键字" clearable
                  @keyup.enter.native="handleQuestionQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuestionQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuestionQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-table v-loading="questionLoading" ref="questionTable" :data="questionList"
              @selection-change="handleQuestionSelectionChange" height="500px">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="题型" align="center" prop="questionType" width="100">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.exam_question_type" :value="scope.row.questionType" />
                </template>
              </el-table-column>
              <el-table-column label="题目名称" align="center" prop="questionTitle" show-overflow-tooltip />
              <el-table-column label="分值" align="center" prop="questionScore" width="80" />
              <el-table-column label="难度" align="center" prop="difficult" width="80" />
              <el-table-column label="题库" align="center" prop="outline" show-overflow-tooltip />
            </el-table>

            <!-- 添加分页组件 -->
            <pagination v-show="questionTotal > 0" :total="questionTotal" :page.sync="questionQueryParams.pageNum"
              :limit.sync="questionQueryParams.pageSize" @pagination="getQuestionList" />
          </div>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 智能生成配置弹窗 -->
    <el-dialog :title="'智能生成试卷'" :visible.sync="smartGenerate.open" width="600px" append-to-body>
      <el-form ref="smartGenerateForm" :model="smartGenerate.form" label-width="100px">
        <!-- 人员类型多选 -->
        <el-form-item label="人员类型" prop="peopleTypes">
          <div class="people-type-selection">
            <el-select v-model="smartGenerate.form.peopleTypes" multiple placeholder="请选择人员类型"
              @change="handlePeopleTypeChange" style="width: calc(100% - 110px)">
              <el-option v-for="item in peopleTypeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" size="small" @click="openBatchSelectDialog"
              style="margin-left: 10px;">批量筛选</el-button>
          </div>
        </el-form-item>

        <!-- 关联的题库名称展示 -->
        <el-form-item label="关联题库">
          <!-- <div style="margin-bottom: 10px; display: flex; justify-content: flex-end;">
            <el-button type="primary" size="mini" @click="applyQuickFilter">快速筛选</el-button>
          </div> -->
          <div class="title-list-container">
            <el-tag v-for="title in relatedTitles" :key="title" style="margin-right: 5px;" closable
              @close="removeRelatedTitle(title)">
              {{ title }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 题型数量配置 -->
        <el-form-item label="题目配置">
          <div class="question-config-container">
            <div v-for="type in questionTypes" :key="type.value" class="config-item">
              <span class="type-label">{{ type.label }}</span>
              <el-input-number v-model="smartGenerate.form.typeCount[type.value]" :min="0" :max="99" size="small"
                controls-position="right" class="count-input">
              </el-input-number>
            </div>
          </div>
        </el-form-item>

        <!-- 修改计算分值的展示方式 -->
        <div
          style="text-align: right; margin-top: 15px; display: flex; align-items: center; justify-content: flex-end;">
          <el-button type="info" plain size="small" @click="calculateEstimatedScore"
            :loading="smartGenerate.calculating">
            计算实际分值
          </el-button>
          <span v-if="smartGenerate.totalScore !== undefined" style="margin-left: 10px;">
            总分：<span style="color: #409EFF; font-weight: bold;">{{ smartGenerate.totalScore }}</span> 分
          </span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="generateQuestions">确 定</el-button>
        <el-button @click="cancelSmartGenerate">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量筛选人员类型弹窗 -->
    <el-dialog
      title="人员类型选择"
      :visible.sync="batchSelect.visible"
      width="800px"
      append-to-body
    >
      <el-form label-width="100px" label-position="left" style="padding: 0 10px;">

        <!-- 列表 -->
        <el-table
          :data="shortTitleList"
          highlight-current-row
          @current-change="handleShortTitleSelect"
          height="300"
          border
          style="margin-bottom: 15px; border-radius: 6px; overflow: hidden;"
        >
          <el-table-column
            label="试卷类型"
            prop="titleName"
            align="center"
            header-align="center"
          />
          <el-table-column
            label="人员类型"
            prop="peopleTypes"
            align="center"
            header-align="center"
          />
        </el-table>

        <!-- 输入框 -->
        <el-form-item label="人员类型" style="margin-top: 12px;">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入人员类型名称，以逗号分隔（中英文逗号均可）"
            v-model="batchSelect.input"
            style="font-size: 13px;"
          />
        </el-form-item>

        <!-- 提示 -->
        <div style="background: #fef4f4; color: #e74c3c; font-size: 12px; padding: 6px 10px; border-radius: 4px; margin: -4px 0 0 100px; width: calc(100% - 110px);">
          💡 点击上方列表可自动填充人员类型
        </div>

      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" @click="applyBatchSelect">确 定</el-button>
        <el-button @click="batchSelect.visible = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listPaper, getPaper, delPaper, addPaper, updatePaper, generatePaperQuestions } from "@/api/exam/paper";
import { listQuestion, getQuestion } from "@/api/exam/question";
import { listPeopleTitle, listPeopleTitleByPost,listPeopleTitleSummary } from "@/api/exam/peopleTitle";

export default {
  name: "Paper",
  dicts: ['exam_question_type', 'job_category'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试试卷表格数据
      paperList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        score: null,
        suggestTime: null,
        deleted: null,
        jobCategory: null,
        outline: null
      },
      // 表单参数
      form: {
        examPaperQuestions: [],
        outline: null
      },
      // 表单校验
      rules: {
        // outline: [
        //   { required: true, message: "题库不能为空", trigger: "blur" }
        // ]
      },

      // 题目列表相关
      questionList: [],
      questionLoading: false,
      questionTotal: 0,
      questionQueryParams: {
        pageNum: 1,
        pageSize: 10,
        questionType: null,
        jobCategory: null,
        outline: null
      },
      questionTablePreSection: [], // 记录表格前面的部分数据，用于删除时判断是否有关联数据

      // 试卷绑定的题目列表相关
      paperQuestionloading: false,

      // 智能生成相关数据
      smartGenerate: {
        open: false,
        form: {
          peopleTypes: [],
          typeCount: {
            1: 0,
            2: 0,
            3: 0
          }
        },
        totalScore: undefined,
        calculating: false
      },
      // 批量筛选相关
      batchSelect: {
        visible: false,
        input: ""
      },
      // 人员类型选项
      peopleTypeOptions: [],
      // 关联的题库名称
      relatedTitles: [],
      shortTitleList: [], // 这里存接口返回的 shortTitles 数据
      selectedRow: null,   // 当前选中的行
      // 题型选项
      questionTypes: [
        { label: '单选题', value: '1' },
        { label: '多选题', value: '2' },
        { label: '判断题', value: '3' }
      ]
    };
  },
  created() {
    this.getList();
    this.getQuestionList();
  },
  methods: {
    /** 查询考试试卷列表 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then(response => {
        // console.log('试卷列表', response)
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /**
     * 题目相关
     */
    getQuestionList() {
      this.questionLoading = true;
      listQuestion(this.questionQueryParams).then(response => {
        this.questionList = response.rows;
        this.questionTotal = response.total;
        // 等待表格完全渲染后再恢复选中状态
        setTimeout(() => {
          if (this.form.examPaperQuestions && this.form.examPaperQuestions.length > 0) {
            // 清除所有选中状态
            this.$refs.questionTable.clearSelection();
            // 获取当前页面应该选中的题目
            const currentPageSelected = this.questionList.filter(row =>
              this.form.examPaperQuestions.some(selected => selected.id === row.id)
            );
            // 选中这些题目
            currentPageSelected.forEach(row => {
              this.$refs.questionTable.toggleRowSelection(row, true);
            });
            // 更新当前页面的选中记录
            this.questionTablePreSection = currentPageSelected;
          }
        }, 100);
        this.questionLoading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuestionQuery() {
      this.questionQueryParams.pageNum = 1;
      this.getQuestionList();
    },
    /** 重置按钮操作 */
    resetQuestionQuery() {
      this.resetForm("queryForm");
      this.questionQueryParams.pageNum = 1;
      this.questionQueryParams.pageSize = 10;
      this.handleQuery();
    },
    // 获取 shortTitles 列表
    getShortTitleList() {
      listPeopleTitleSummary().then(res => {
        this.shortTitleList = res.rows
        // console.log('shortTitleList', this.shortTitleList)
      })
    },
    // 选中行事件
    handleShortTitleSelect(row) {
      if (row && row.peopleTypes) {
        this.batchSelect.input = row.peopleTypes
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        this.form.name = `${year}年${month}月${row.titleName}`;
      } else {
        this.batchSelect.input = ''
      }
    },
    handleQuestionSelectionChange(selection) {
      // 初始化 examPaperQuestions 如果不存在
      if (!this.form.examPaperQuestions) {
        this.form.examPaperQuestions = [];
      }

      // 仅处理当前页的选中变化
      const currentPageIds = this.questionList.map(item => item.id);

      // 获取当前已有题目的ID集合
      const existingIds = new Set(this.form.examPaperQuestions.map(q => q.id));

      // 移除当前页中取消选中的题目
      this.form.examPaperQuestions = this.form.examPaperQuestions.filter(
        question => !currentPageIds.includes(question.id) || selection.some(s => s.id === question.id)
      );

      // 添加新选中的题目
      selection.forEach(item => {
        // 如果题目不存在，才添加
        if (!existingIds.has(item.id)) {
          this.form.examPaperQuestions.push({
            id: item.id,
            questionTitle: item.questionTitle,
            questionType: item.questionType,
            questionScore: item.questionScore,
            outline: item.outline,
            selected: true,
            questionAnswer: item.questionAnswer,
            questionAnswerExplain: item.questionAnswerExplain,
            questionText: item.questionText


          });
          existingIds.add(item.id);
        }
      });
    },


    /**
     * 试卷绑定的题目相关
     */
    handlePaperQuestionDelete(row) {
      const index = this.form.examPaperQuestions.findIndex(
        (paperItem) => paperItem.id === row.id
      );
      if (index !== -1) {
        this.form.examPaperQuestions.splice(index, 1);
        // 如果当前页面包含这个题目，取消其选中状态
        const tableRow = this.questionList.find((item) => item.id === row.id);
        if (tableRow) {
          this.$refs.questionTable.toggleRowSelection(tableRow, false);
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        // score: null,
        suggestTime: 90,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deleted: null,
        jobCategory: null,
        score: 0,
        examPaperQuestions: [],
        outline: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },


    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试试卷";
      this.$nextTick(() => {
        this.$refs.questionTable.clearSelection()
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPaper(id).then(response => {
        // 确保examPaperQuestions中没有重复的题目
        const uniqueQuestions = [];
        const seenIds = new Set();
        response.data.examPaperQuestions.forEach(question => {
          if (!seenIds.has(question.id)) {
            uniqueQuestions.push(question);
            seenIds.add(question.id);
          }
        });
        // console.log('uniqueQuestions', uniqueQuestions)
        response.data.examPaperQuestions = uniqueQuestions;
        this.form = response.data;
        this.open = true;
        this.title = "修改考试试卷";

        // 等待表格渲染完成后再设置选中状态
        this.$nextTick(() => {
          this.$refs.questionTable.clearSelection();
          this.getQuestionList();
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            console.log('form', this.form)
            updatePaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试试卷编号为"' + ids + '"的数据项？').then(function () {
        return delPaper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/paper/export', {
        ...this.queryParams
      }, `paper_${new Date().getTime()}.xlsx`)
    },

    // 计算总分
    calculateTotalScore() {
      if (this.form.examPaperQuestions) {
        this.form.score = this.form.examPaperQuestions.reduce((total, question) => {
          return total + (question.questionScore || 0); // 累加每个题目的分数
        }, 0);
      }
    },

    // 打开智能生成配置
    openSmartGenerate() {
      // 重置智能生成表单数据
      this.resetSmartGenerateForm();
      this.smartGenerate.open = true;
      this.loadPeopleTypes();
      this.getShortTitleList();
    },

    // 重置智能生成表单
    resetSmartGenerateForm() {
      this.smartGenerate.form = {
        peopleTypes: [],
        typeCount: {
          1: 0,
          2: 0,
          3: 0
        }
      };
      this.smartGenerate.totalScore = undefined;
      this.smartGenerate.calculating = false;
      this.relatedTitles = [];
      // 如果表单引用存在，也重置表单验证状态
      if (this.$refs.smartGenerateForm) {
        this.$refs.smartGenerateForm.clearValidate();
      }
    },

    // 取消智能生成
    cancelSmartGenerate() {
      this.smartGenerate.open = false;
      this.resetSmartGenerateForm();
    },

    // 加载人员类型选项
    async loadPeopleTypes() {
      try {
        const response = await listPeopleTitleByPost({
          pageNum: 1,
          pageSize: 10000,
        });
        // 提取不重复的 peopleType
        const types = [...new Set(response.rows.map(item => item.peopleType))];
        this.peopleTypeOptions = types.map(type => ({
          label: type,
          value: type
        }));
      } catch (error) {
        console.error('加载人员类型失败', error);
      }
    },

    // 处理人员类型变化
    async handlePeopleTypeChange(values) {
      if (!values.length) {
        this.relatedTitles = [];
        return;
      }

      try {
        // 使用POST方法查询，避免URI过长
        const response = await listPeopleTitleByPost({
          pageNum: 1,
          pageSize: 10000,
          peopleType: values.join(',')
        });
        // 获取题库名称列表并去重（替换而不是累积）
        const newTitles = response.rows.map(item => item.titleName);
        this.relatedTitles = [...new Set(newTitles)];
      } catch (error) {
        console.error('加载关联题库失败', error);
      }
    },

    // 计算实际分值
    async calculateEstimatedScore() {
      if (!this.relatedTitles.length) {
        this.$message.warning('请先选择人员类型');
        return;
      }

      const totalCount = Object.values(this.smartGenerate.form.typeCount).reduce((a, b) => a + b, 0);
      if (totalCount === 0) {
        this.$message.warning('请至少选择一种题型的数量');
        return;
      }

      this.smartGenerate.calculating = true;
      try {
        const params = {
          titleNames: this.relatedTitles,
          typeCount: this.smartGenerate.form.typeCount
        };

        const response = await generatePaperQuestions(params);

        if (response.code === 200) {
          const generatedQuestions = response.data;
          this.smartGenerate.totalScore = generatedQuestions.reduce((total, question) =>
            total + (question.questionScore || 0), 0
          );
        } else {
          this.$modal.msgError(response.msg || '计算分值失败');
        }
      } catch (error) {
        this.$modal.msgError('计算分值失败：' + (error.message || '未知错误'));
      } finally {
        this.smartGenerate.calculating = false;
      }
    },

    // 生成试题
    async generateQuestions() {
      if (!this.relatedTitles.length) {
        this.$message.warning('请先选择人员类型');
        return;
      }

      const totalCount = Object.values(this.smartGenerate.form.typeCount).reduce((a, b) => a + b, 0);
      if (totalCount === 0) {
        this.$message.warning('请至少选择一种题型的数量');
        return;
      }

      this.$modal.loading("正在生成试题，请稍候...");
      try {
        const params = {
          titleNames: this.relatedTitles,
          typeCount: this.smartGenerate.form.typeCount
        };

        const response = await generatePaperQuestions(params);

        if (response.code === 200) {
          const generatedQuestions = response.data;
          // 清空已有题目，完全重新生成
          this.form.examPaperQuestions = generatedQuestions.map(question => ({
            id: question.id,
            questionTitle: question.questionTitle,
            questionType: question.questionType,
            questionScore: question.questionScore,
            questionAnswer: question.questionAnswer,
            questionText: question.questionText,
            questionAnswerExplain: question.questionAnswerExplain,
            difficult: question.difficult,
            deleted: question.deleted,
            jobCategory: question.jobCategory,
            outline: question.outline,
            createBy: question.createBy,
            createTime: question.createTime,
            updateBy: question.updateBy,
            updateTime: question.updateTime,
            remark: question.remark,
            selected: true
          }));

          // 计算总分
          this.form.score = this.form.examPaperQuestions.reduce((total, q) => total + (q.questionScore || 0), 0);

          // 更新选中题目的数量统计
          this.selectedQuestionCount = {
            total: this.form.examPaperQuestions.length,
            types: this.form.examPaperQuestions.reduce((acc, q) => {
              acc[q.questionType] = (acc[q.questionType] || 0) + 1;
              return acc;
            }, {})
          };

          // 关闭弹窗并重置表单数据
          this.smartGenerate.open = false;
          this.resetSmartGenerateForm();
          this.$modal.msgSuccess('试题生成成功');
        } else {
          this.$modal.msgError(response.msg || '生成试题失败');
        }
      } catch (error) {
        this.$modal.msgError('生成试题失败：' + (error.message || '未知错误'));
      } finally {
        this.$modal.closeLoading();
      }
    },

    // 移除关联题库
    removeRelatedTitle(title) {
      const index = this.relatedTitles.indexOf(title);
      if (index !== -1) {
        this.relatedTitles.splice(index, 1);
      }
    },

    // 快速筛选题库
    applyQuickFilter() {
      this.$prompt('请输入要筛选的题库列表（用逗号分隔）', '快速筛选', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: '1,15,18,19,21,22,23,24,29-1,29-2,37,4,43,44,45,46,7,Z,三十五项严重违章'
      }).then(({ value }) => {
        if (!value) return;

        // 分割用户输入的题库列表
        const filterItems = value.split(',').map(item => item.trim());

        // 获取当前所有可用题库
        this.loadAllAvailableTitles().then(allTitles => {
          if (!allTitles || !allTitles.length) {
            this.$message.warning('未找到可筛选的题库');
            return;
          }

          // 筛选匹配的题库
          const filteredTitles = allTitles.filter(title => {
            // 对于每个标题，检查是否匹配任何一个过滤项
            return filterItems.some(filterItem => {
              // 检查标题是否以过滤项开头
              if (title.startsWith(filterItem)) {
                // 检查匹配部分后面是否紧跟"-"或者没有内容
                const remaining = title.substring(filterItem.length);
                return remaining === '' || remaining.startsWith('-');
              }
              return false;
            });
          });

          if (filteredTitles.length === 0) {
            this.$message.warning('未找到匹配的题库');
            return;
          }

          // 更新关联题库
          this.relatedTitles = filteredTitles;
          this.$message.success(`已筛选出 ${filteredTitles.length} 个匹配的题库`);
        });
      }).catch(() => {
        // 用户取消输入
      });
    },

    // 加载所有可用的题库
    async loadAllAvailableTitles() {
      try {
        const response = await listPeopleTitleByPost({
          pageNum: 1,
          pageSize: 10000
        });
        return [...new Set(response.rows.map(item => item.titleName))];
      } catch (error) {
        console.error('加载题库失败', error);
        this.$message.error('加载题库失败');
        return [];
      }
    },

    // 打开批量筛选对话框
    openBatchSelectDialog() {
      this.batchSelect.visible = true;
      this.batchSelect.input = "";
    },

    // 应用批量筛选
    applyBatchSelect() {
      if (!this.batchSelect.input.trim()) {
        this.$message.warning('请输入人员类型名称');
        return;
      }

      // 处理输入的字符串，支持中英文逗号分隔
      const inputText = this.batchSelect.input.replace(/，/g, ',');
      const typeNames = inputText.split(',').map(name => name.trim()).filter(name => name);

      if (typeNames.length === 0) {
        this.$message.warning('未找到有效的人员类型名称');
        return;
      }

      // 匹配现有选项
      const matchedTypes = [];
      const unmatchedTypes = [];

      typeNames.forEach(typeName => {
        const option = this.peopleTypeOptions.find(opt => opt.label === typeName || opt.value === typeName);
        if (option) {
          matchedTypes.push(option.value);
        } else {
          unmatchedTypes.push(typeName);
        }
      });

      // 更新选择
      this.smartGenerate.form.peopleTypes = matchedTypes;

      // 关闭弹窗
      this.batchSelect.visible = false;

      // 触发人员类型变化处理
      this.handlePeopleTypeChange(this.smartGenerate.form.peopleTypes);

      // 显示结果
      if (unmatchedTypes.length > 0) {
        this.$message({
          type: 'warning',
          message: `成功匹配 ${matchedTypes.length} 项，未匹配 ${unmatchedTypes.length} 项`,
          duration: 3000
        });
      } else {
        this.$message({
          type: 'success',
          message: `成功匹配 ${matchedTypes.length} 项人员类型`,
          duration: 3000
        });
      }
    }
  },
  watch: {
    // 监听 form.examPaperQuestions 变化
    "form.examPaperQuestions": {
      handler() {
        this.calculateTotalScore(); // 每次 form.examPaperQuestions 变化时重新计算总分
      },
      deep: true, // 深度监听，以便捕获对象内部的变化
    },
  },
};
</script>

<style lang="scss" scoped>
.selected-questions-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.question-select-area {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.el-table {
  margin-top: 10px;
}

.title-list-container {
  margin: 10px 0;
  max-height: 120px;
  min-height: 40px;
  overflow-y: auto;
  padding: 5px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;

  .el-tag {
    margin-bottom: 5px;
    margin-right: 5px;

    &:last-child {
      margin-right: 0;
    }
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #909399;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: #F5F7FA;
  }
}

.question-config-container {
  padding: 15px;
  background-color: #f8f9fb;
  border-radius: 4px;

  .config-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .type-label {
      width: 80px;
      color: #606266;
      font-size: 14px;
    }

    .count-input {
      width: 120px;
      margin-left: 10px;

      :deep(.el-input-number__decrease),
      :deep(.el-input-number__increase) {
        border-radius: 0;
      }

      :deep(.el-input__inner) {
        text-align: center;
      }
    }
  }
}

.smart-generate-btn {
  margin-bottom: 20px;
  text-align: right;
}

.people-type-selection {
  display: flex;
  align-items: center;
}
</style>
